package com.googlecode.pwlodars.piteststat.writer.content;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.googlecode.pwlodars.piteststat.content.PitestSingleResult;

public class PitestResultFilesParser {

	private static Pattern mutationPattern=Pattern.compile("Mutation coverage (\\d+)%");
	
	public List<PitestSingleResult> parseResults(PitResultFileInfo pitResultFileInfo) {

		final Document document = Jsoup.parse(pitResultFileInfo.getContent());
		Elements resultElements = document.getElementsByClass("unit");
		
		List<PitestSingleResult> parsedResults = parseElements(resultElements);
		
		updaterunDate(pitResultFileInfo, parsedResults);
		return parsedResults;
		
	}

	private void updaterunDate(PitResultFileInfo pitResultFileInfo, List<PitestSingleResult> parseElements) {
		for (PitestSingleResult pitestSingleResult : parseElements) {
			pitestSingleResult.setRunDate(pitResultFileInfo.getRunDate());
		}
	}

	private List<PitestSingleResult> parseElements(Elements resultElements) {
		List<PitestSingleResult> results=new LinkedList<PitestSingleResult>();
		for (Element element : resultElements) {
			if(!hasResult(element)){
				continue;
			}
			String fullClassName = parseFullClassName(element);
			int mutationCoverage=parseMutationCoverage(element);
			PitestSingleResult pitestResult = PitestSingleResult.withFuillClassName(fullClassName,mutationCoverage);
			results.add(pitestResult);
		}
		
		return results;
	}

	private boolean hasResult(Element element) {
		return element.html().contains("<a");
	}

	private int parseMutationCoverage(Element element) {
		Element mutationCoverageElement = element.getElementsByClass("mut").get(0);
		Matcher mutationCoverageMatcher = mutationPattern.matcher(mutationCoverageElement.text());
		mutationCoverageMatcher.find();
		return Integer.parseInt(mutationCoverageMatcher.group(1));
	}

	private String parseFullClassName(Element element) {
		Element linkElement = element.getElementsByTag("a").get(0);
		String linkText = linkElement.text();
		
		String ending = resolveRedundantLineEnding(linkText);
		return linkText.substring(0, linkText.indexOf(ending));
	}

	/**
	 * To support older versions of pitest
	 * where class names ended with ".html"
	 * @param linkText
	 * @return
	 */
	private String resolveRedundantLineEnding(String linkText) {
		String ending;
		if(linkText.contains(".java.html")){
			ending = ".java.html";
		}else{
			ending = ".html";
		}
		return ending;
	}

}
